package com.word.controller;

import com.alibaba.fastjson.JSONObject;
import com.word.util.RandomIdUtil;
import com.word.util.WordUtil;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.apache.xmlbeans.XmlException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.path}")
    private String filePath;

    @PostMapping("/upload")
    public JSONObject readWordContent(@RequestParam("file")MultipartFile file,@RequestParam("keys") String keys) throws IOException, OpenXML4JException, XmlException {
        String fileName = file.getOriginalFilename();
        String extend = "."+ FilenameUtils.getExtension(fileName);
        String newFileName = "real_"+ RandomIdUtil.createRandomId() +extend;
        File fileDir = new File(filePath + newFileName);
        if(!fileDir.getParentFile().exists()){
            fileDir.getParentFile().mkdirs();
        }
        String content = "";
        try{
            file.transferTo(fileDir);
            content = WordUtil.readText(filePath+newFileName,extend);
        }catch (IOException e){
            e.printStackTrace();
        }
        JSONObject result = new JSONObject();
        result.put("content",content);
        return result;
    }
}
